package com.moehu.back.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.moehu.back.dao.DynamicDao;
import com.moehu.back.dao.OpusDao;
import com.moehu.back.dao.TagDao;
import com.moehu.back.dao.UserDao;
import com.moehu.back.model.*;
import com.moehu.back.model.response.OpusInfoResponseModel;
import com.moehu.back.model.response.OpusSearchUser;
import com.moehu.back.model.response.RankingResponseModel;
import com.moehu.back.service.OpusService;
import com.moehu.back.service.TokenService;
import com.moehu.back.utils.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OpusServiceImpl extends BaseServiceImpl implements OpusService {

    @Autowired
    OpusDao opusDao;

    @Autowired
    TagDao tagDao;

    @Autowired
    UserDao userDao;

    @Autowired
    DynamicDao dynamicDao;

    @Autowired
    public HttpServletRequest request;

    @Autowired
    TokenService tokenService;

    @Override
    public ResultModel OpusList(PagingModel pagingModel) {
        Page page = PageHelper.startPage(pagingModel.getPage(), pagingModel.getCount());
        List<OpusModel> list = opusDao.getOpusList();

        return list.isEmpty() ? ResultUtils.Error("没有数据") : ResultUtils.Success(Tool.CountPage(page, list));
    }


    @Override
    public ResultModel FollowOpusList(PagingModel pagingModel) {
        // 从token中获取用户id，并存储到 PagingModel 中
        pagingModel.setUserid(tokenService.uid());

        // 获取用户A关注用户B的id
        List<Integer> FollowToUserIds = opusDao.getUserFollowId(pagingModel.getUserid());

        log.info("FollowToUserIds============ {}", FollowToUserIds);

        // 根据用户B的id去找用户B的作品
        Page page = PageHelper.startPage(pagingModel.getPage(), pagingModel.getCount());
        List<OpusModel> list = opusDao.getFollowList(FollowToUserIds);

        return list.isEmpty() ? ResultUtils.Error("没有数据") : ResultUtils.Success(Tool.CountPage(page,list));
    }

    @Override
    public ResultModel RankingOpusList(PagingModel pagingModel) {
        Page page = PageHelper.startPage(pagingModel.getPage(), pagingModel.getCount());
        List<RankingResponseModel> list = opusDao.getRankingOpusList();
        return list.isEmpty() ? ResultUtils.Error("没有数据") : ResultUtils.Success(Tool.CountPage(page, list));
    }

    @Override
    public ResultModel addFollowUser(Integer id) {
        Integer user_source_id = tokenService.uid();
        if (user_source_id.equals(id)) {
            return ResultUtils.Error("不能关注自己");
        } else {
            Integer addid = opusDao.addFollowUser(user_source_id,id);
            // 取消关注
            if (addid == 0) {
                Integer deleteid = opusDao.cancelFollowUser(user_source_id,id);
                return ResultUtils.SuccessStatus("取消关注成功");
            // 关注
            } else {
                return ResultUtils.SuccessStatus("关注成功");
            }
        }
    }

    @Override
    public ResultModel checkUserIsFollow(Integer id) {
        Integer user_source_id = tokenService.uid();
        Integer checkStatus = opusDao.checkFollowUser(user_source_id,id);
        log.info("checkStatus ====== {}", checkStatus);
        if (checkStatus == 0) {
            return ResultUtils.Success(false);
        } else {
            return ResultUtils.Success(true);
        }
    }


    @Override
    public ResultModel getOpusInfo(Integer id, String type) {
        // 获取 作品 的详情
        OpusInfoResponseModel info = opusDao.getOpusInfo(id);
        if (info == null) {
            return ResultUtils.Error("没有数据~");
        } else {
            if (type == "app") {
                // 获取 作品的评论
//            List<CommentModel> opusComment = opusDao.getUserComment(id, 0, 1);
//            opusComment = getComment(opusComment);
                // 获取该 作品 下面用户的最新作品
                List<OpusModel> NewOpus = opusDao.getNewsOpus(info.getUser_id(), id);
//            info.setComment(opusComment);
                info.setNews_opus(NewOpus);
            }

            // 获取该 作品 的 发布者
            UserModel userInfo = userDao.getFindById(info.getUser_id());

            // 获取该 作品 的 标签
            List<TagModel> opusTag = tagDao.getOpusTag(id);

            List<ImgModel> imgArr = opusDao.getOpusImg(id);

            info.setUser_info(userInfo);
            info.setTags(opusTag);
            info.setOpus_imgs(imgArr);

            log.info("ip地址为 ====== {}", IpUtil.getIpAddr());

            // 向浏览量表中插入数据，但是插入前判断，是否已经浏览过了
            // 0 浏览过了，1 未浏览
            Integer insterId = opusDao.isSeeOpus(IpUtil.getIpAddr(),id);
            // 未浏览，那么增加一条浏览记录
            if (insterId == 1) {
                opusDao.addSeeCount(id);
            }
            return ResultUtils.Success(info);
        }
    }

    @Override
    public ResultModel collectionOpus(Integer opus_id) {
        Integer Staus = opusDao.CollectionOpus(tokenService.uid(), opus_id);
        if (Staus == 1) {
            opusDao.addCollectionCount(opus_id);
            return ResultUtils.SuccessStatus("收藏成功");
        } else {
            opusDao.reduceCollectionCount(opus_id);
            Integer cancelStatus = opusDao.cancelCollectionOpus(tokenService.uid(), opus_id);
            return ResultUtils.SuccessStatus("已取消收藏");
        }
    }

    @Override
    public ResultModel collectionOpusList(PagingModel pagingModel) {
        Page page = PageHelper.startPage(pagingModel.getPage(), pagingModel.getCount());
        List<OpusModel> list = opusDao.OpusList(pagingModel.getUserid());
        if (list.isEmpty()) {
            return ResultUtils.SuccessStatus("暂无收藏");
        } else {
            return ResultUtils.Success(Tool.CountPage(page, list));
        }
//        List<Map<String, Integer>> opusIdArr = opusDao.getCollectionUserId(pagingModel.getUserid());
//        if (opusIdArr.isEmpty()) {
//            return ResultUtils.SuccessStatus("暂无收藏");
//        } else {
//
//            if (list.isEmpty()) {
//                return ResultUtils.SuccessStatus("暂无收藏");
//            } else {
//                return ResultUtils.Success(Tool.CountPage(page, list));
//            }
//        }
    }

    @Override
    public ResultModel upvoteOpus(Map<String, String> opus) {

        // 对作品进行点赞
        if (opus.get("opus_id") != "") {
            Integer opusId = Integer.parseInt(opus.get("opus_id"));
            Integer isHave = opusDao.upvoteOpus(tokenService.uid(), opusId);
            if (isHave == 0) {
                log.info("作品没有点赞");
                // 增加一条点赞记录
                opusDao.addUpvoteOpus(tokenService.uid(), opusId);
                // 增加作品的点赞数
                opusDao.addUpvoteCount(opusId);
                return ResultUtils.SuccessStatus("作品点赞成功");
            } else {
                // 删除点赞记录
                Integer delete = opusDao.deleteUpvoteOpus(tokenService.uid(), opusId);
                // 作品的点赞数 - 1
                try {
                    opusDao.reduceUpvoteCount(opusId);
                } catch (Exception e) {
                    log.info("不能为负数");
                }
                log.info("作品点过点赞了");
                return ResultUtils.SuccessStatus("取消作品点赞");
            }

        // 对动态进行点赞
        } else if (opus.get("dynamic_id") != "") {
            Integer dynamicId = Integer.parseInt(opus.get("dynamic_id"));
            // 查询动态是否被点赞
            Integer dy = opusDao.upvoteDynamic(tokenService.uid(), dynamicId);
            // 没有点赞
            if (dy == 0) {
                log.info("动态没有点赞");
                // 增加一条动态的点赞记录
                opusDao.addUpvoteDynamic(tokenService.uid(), dynamicId);
                // 增加动态的点赞数量
                opusDao.UpvoteDynamicCount(dynamicId);
                return ResultUtils.SuccessStatus("动态点赞成功");
            } else {
                // 删除点赞记录
                opusDao.deleteUpvoteDynamic(tokenService.uid(), dynamicId);
                // 作品的点赞数 - 1
                try {
                    opusDao.reduceUpvoteDynamicCount(dynamicId);
                } catch (Exception e) {
                    log.info("不能为负数");
                }
                log.info("动态点过点赞了");
                return ResultUtils.SuccessStatus("取消动态点赞");
            }
        } else {
            return ResultUtils.SuccessStatus("参数错误");
        }
    }

    @Override
    public ResultModel checkOpusIsUpvote(String opus_id, String dynamic_id) {
        if (opus_id != "") {
            if (opusDao.upvoteOpus(tokenService.uid(), Integer.parseInt(opus_id)) == 0) {
                return ResultUtils.Success(false);
            } else {
                return ResultUtils.Success(true);
            }
        } else if (dynamic_id != "") {
            if (opusDao.upvoteDynamic(tokenService.uid(), Integer.parseInt(dynamic_id)) == 0) {
                return ResultUtils.Success(false);
            } else {
                return ResultUtils.Success(true);
            }
        } else {
            return ResultUtils.SuccessStatus("参数错误");
        }
    }

    @Override
    public ResultModel pushOpus(PushOpusModel opus) {
        opus.setUser_id(tokenService.uid());
        opus.setOpus_img(opus.getOpus_imgs()[0]);

        Integer newOpusId = opusDao.addOpus(opus);

        if (newOpusId == 1) {
            // 先插入作品，然后拿到插入作品的id，之后再插入 moehu_img 和 moehu_tags 表
            log.info("opus.getOpus_id() ===== {}", opus.getOpus_id());

            String[] tagArr = opus.getOpus_tags();
            List<TagModel> tags = new ArrayList<>();
            for(String title:tagArr){
                TagModel newJson = new TagModel();
                newJson.setOpus_id(opus.getOpus_id());
                newJson.setTags_title(title);
                newJson.setUser_id(opus.getUser_id());
                tags.add(newJson);
            }
            opusDao.OpusCreatedTag(tags);

            String[] imgArr = opus.getOpus_imgs();
            List<ImgModel> imgs = new ArrayList<>();
            for(String url:imgArr) {
                ImgModel imgList = new ImgModel();

                // 发送请求获取阿里云oss图片的宽高
                JSONObject ossImg = HttpClient.doGet(url+"?x-oss-process=image/info");

                imgList.setImg_width(HttpClient.GetWidth(ossImg));
                imgList.setImg_height(HttpClient.GetHeight(ossImg));

                imgList.setImg_url(url);
                imgList.setOpus_id(opus.getOpus_id());
                imgList.setUser_id(opus.getUser_id());
                imgs.add(imgList);
            }
            opusDao.OpusCreatedImg(imgs);

            // 是否需要同步作品至动态
            // true 需要同步作品到动态中 false 什么都不执行
            if (opus.getOpus_syncDynamic()) {
                DynamicModel Dynamic = new DynamicModel();
                Dynamic.setOpus_id(opus.getOpus_id());
                Dynamic.setUser_id(opus.getUser_id());
                Dynamic.setDynamic_introduce(opus.getOpus_introduce());
                Integer dyId = dynamicDao.addDynamic(Dynamic);
            }

            return ResultUtils.SuccessStatus("作品发布成功");
        } else {
            return ResultUtils.Error("作品发布失败");
        }

    }


    @Override
    public ResultModel checkOpusIsCollection(Integer opus_id) {
        Integer isCollection = opusDao.checkOpusIsCollection(opus_id, tokenService.uid());
        log.info("isCollection ======= {}", isCollection);
        if (isCollection == 1) {
            return ResultUtils.Success(true);
        } else {
            return ResultUtils.Success(false);
        }
    }

    @Override
    public ResultModel collectionOpusInfo(Integer id) {
        List<ImgModel> InfoImg = opusDao.collectionOpusInfo(id);
        if (InfoImg.isEmpty()) {
            return ResultUtils.Error("没有数据");
        } else {
            return ResultUtils.Success(InfoImg);
        }
    }


    @Override
    public ResultModel OpusSearch(Map<String, String> Opus) throws Exception {
        // 查找作品
        List<String> keywordList = IKAnalyzerSupport.iKSegmenterToList(Opus.get("keyword"));
        log.info("分词后关键词为: ===== {}", keywordList);
        if (Opus.get("type").equals("opus")) {
            Page page = PageHelper.startPage(Integer.parseInt(Opus.get("page")), Integer.parseInt(Opus.get("count")));
            List<OpusModel> opusList = opusDao.OpusSearch(keywordList);
            log.info("作品搜索的数据 ==== {}", opusList);

            if (opusList.isEmpty()) {
                return ResultUtils.Error("暂无数据");
            } else {
                return ResultUtils.Success(Tool.CountPage(page, opusList, keywordList));
            }

        // 查找用户
        } else if (Opus.get("type").equals("user")) {
            Integer user_source_id = tokenService.uid();
            Page page = PageHelper.startPage(Integer.parseInt(Opus.get("page")), Integer.parseInt(Opus.get("count")));
            List<OpusSearchUser> userList = opusDao.UserSearch(keywordList);
            for (OpusSearchUser u: userList) {
                Integer status = opusDao.checkFollowUser(user_source_id, u.getUser_id());
                if (status == 0) {
                    u.setHave_follow(false);
                } else {
                    u.setHave_follow(true);
                }
            }
            if (userList.isEmpty()) {
                return ResultUtils.Error("暂无数据");
            } else {
                return ResultUtils.Success(Tool.CountPage(page, userList, keywordList));
            }

        // 查找标签
        } else if (Opus.get("type").equals("tag")) {
            Page page = PageHelper.startPage(Integer.parseInt(Opus.get("page")), Integer.parseInt(Opus.get("count")));
            List<OpusModel> tagList = opusDao.TagSearch(keywordList);
            if (tagList.isEmpty()) {
                return ResultUtils.Error("暂无数据");
            } else {
                return ResultUtils.Success(Tool.CountPage(page, tagList, keywordList));
            }
        } else {
            return ResultUtils.Error("不支持此查询");
        }
    }


    @Override
    public ResultModel OpusAudit(Map<String, String> Opus) {
        Page page = PageHelper.startPage(Integer.parseInt(Opus.get("page")), Integer.parseInt(Opus.get("count")));
        log.info("opus_title == {}", Opus.get("opus_title"));
        log.info("opus_status == {}", Opus.get("opus_status"));
        log.info("opus_type == {}", Opus.get("opus_type"));
        log.info("opus_original == {}", Opus.get("opus_original"));
        List<OpusModel> res = opusDao.opusAudit(
                Opus.get("opus_title"),
                Opus.get("opus_status"),
                Opus.get("opus_type"),
                Opus.get("opus_original")
        );
        if (res.isEmpty()) {
            List a = new ArrayList();
            return ResultUtils.Success(a);
        } else {
            return ResultUtils.Success(Tool.CountPage(page,res));
        }
    }

    @Override
    public ResultModel Approved(Map<String, Integer> Opus) {
        Integer up = opusDao.updateOpusStatus(Opus.get("opus_id"), Opus.get("opus_status"));
        if (up == 1) {
            return ResultUtils.SuccessStatus("成功");
        } else {
            return ResultUtils.SuccessStatus("失败");
        }
    }

    @Override
    public ResultModel MyOpusList(PagingModel user) {
        Page page = PageHelper.startPage(user.getPage(), user.getCount());
        List<OpusModel> res = opusDao.MyOpusList(user.getUserid());
        if (res.isEmpty()) {
            return ResultUtils.Error("暂无数据");
        } else {
            return ResultUtils.Success(Tool.CountPage(page,res));
        }
    }

}
